import React from 'react'
import { connect } from 'react-redux'
import { validForm as validFormDuck } from 'ducks'
import { Dropdown } from 'semantic-ui-react'

function ValidFieldWapper(WrappedComponent, mapValueToObject, mapActionToObject) {
  const mapStateToProps = (state, ownProps) => ({
    value: validFormDuck.selectors.fieldValue(state, ownProps.name),
  })

  const mapDispatchToProps = {
    actionFieldChange: validFormDuck.creators.actionFieldChange,
  }

  const FieldWrapper = ({
    value, actionFieldChange, name, rule, children, ...otherProps
  }) => (
    <WrappedComponent
      {...mapValueToObject(value)}
      {...mapActionToObject(actionFieldChange, name, rule)}
      {...otherProps}
    >
      {children}
    </WrappedComponent>
  )

  return connect(
    mapStateToProps,
    mapDispatchToProps,
  )(FieldWrapper)
}

export const WrapperDropdown = ValidFieldWapper(
  Dropdown,
  value => ({ value }),
  (action, name, rules) => ({ onChange: (e, { value }) => action(name, value, rules) }),
)
